﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TcpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //开始任务
            test();
        }

        /// <summary>
        /// 测试
        /// </summary>
        private static void test()
        {
            TcpListener server = null;
            Console.Write("请输入监听的端口号：");
            string strPort = Console.ReadLine();
            try
            {
                int port = Convert.ToInt32(strPort);
                IPEndPoint listenPort = new IPEndPoint(IPAddress.Any, port);
                server = new TcpListener(listenPort);//初始化TcpListener的新实例
                server.Start();//开始监听客户端的请求
                Byte[] bytes = new Byte[256];//缓存读入的数据
                String data = null;
                while (true)//循环监听
                {
                    Console.Write("服务已启动...");
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("已连接！");
                    data = null;
                    NetworkStream stream = client.GetStream();//获取用于读取和写入的流对象
                    int i;
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        //将借宿字节的数据转换成一个UTF8字符串
                        data = Encoding.UTF8.GetString(bytes, 0, i);
                        Console.WriteLine("接收消息:{0}", data);
                        Console.Write("发送消息：");
                        data = Console.ReadLine();//服务器发送消息
                        byte[] msg = Encoding.UTF8.GetBytes(data);
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine(msg);
                    }
                    client.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                server.Stop();
            }
            Console.WriteLine("\n按任意键退出...");
        }
    }
}
